//
//  UIView+BgGradient.m
//  WXReader
//
//  Created by huaya on 2025/7/25.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "UIView+BgGradient.h"
// 默认渐变颜色
#define DEFAULT_GRADIENT_LEFT  [UIColor colorWithRed:0.867 green:0.839 blue:1.000 alpha:1.0] // #DDD6FF
#define DEFAULT_GRADIENT_RIGHT [UIColor colorWithRed:0.780 green:0.729 blue:1.000 alpha:1.0] // #C7BAFF
// 渐变层标识
static NSString * const kGradientLayerIdentifier = @"HorizontalGradientBackgroundLayer";

@implementation UIView(BgGradient)

// 为任意视图添加渐变背景
- (void)addGradientBackground{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.bounds;
    
    gradientLayer.colors = @[
        (id)[UIColor colorWithRed:0.906 green:0.890 blue:0.988 alpha:1.0].CGColor,
        (id)[UIColor colorWithRed:0.969 green:0.965 blue:0.988 alpha:1.0].CGColor,
        (id)[UIColor colorWithRed:0.973 green:0.969 blue:0.988 alpha:1.0].CGColor
    ];
    
    gradientLayer.locations = @[@0.0, @0.33, @1.0];
    gradientLayer.startPoint = CGPointMake(0.5, 0.0);
    gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    
    [self.layer insertSublayer:gradientLayer atIndex:0];
}

- (void)addHorizontalGradientBackgroundWithLeftColor:(UIColor *)leftColor
                                          rightColor:(UIColor *)rightColor {

    // 创建渐变层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.name = kGradientLayerIdentifier;
    gradientLayer.frame = self.bounds;
    
    // 设置颜色
    gradientLayer.colors = @[
        (id)leftColor.CGColor,
        (id)rightColor.CGColor
    ];
    
    // 设置左右渐变方向
    gradientLayer.startPoint = CGPointMake(0.0, 0.5); // 左边缘中点
    gradientLayer.endPoint = CGPointMake(1.0, 0.5);   // 右边缘中点
    
    // 添加到视图底层
    [self.layer insertSublayer:gradientLayer atIndex:0];
    
}

- (void)addDefaultHorizontalGradientBackground {
    [self addHorizontalGradientBackgroundWithLeftColor:DEFAULT_GRADIENT_LEFT
                                           rightColor:DEFAULT_GRADIENT_RIGHT];
}
- (void)updateGradientCornerRadius {
    [self.layer.sublayers enumerateObjectsUsingBlock:^(CALayer *layer, NSUInteger idx, BOOL *stop) {
        if ([layer.name isEqualToString:kGradientLayerIdentifier]) {
            layer.cornerRadius = self.layer.cornerRadius;
            *stop = YES;
        }
    }];
}
@end
